package com.code.zjm.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.code.zjm.R;
import com.code.zjm.entity.User;
import com.code.zjm.helper.DBHelper;
import com.getbase.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 主界面
 */
public class MainActivity extends AppCompatActivity {
    private final static String TAG = MainActivity.class.getSimpleName();
    private ListView userList;
    private EditText etSearch;
    private LinearLayout deleteUser;
    private Button btDeleteUser;
    private FloatingActionButton btAddUser;
    private RelativeLayout searchResult;
    private ArrayList<HashMap<String, Object>> users;
    private ArrayList<Integer> deleteId;
    private SimpleAdapter adapter;
    //表示保密状态
    private boolean privacy = false;
    //表示 ListView 处于显示选择联删除联系人的状态
    private boolean isChecking = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i(TAG, "onCreate: >>>>>");

        //创建数据库管理对象
        DBHelper helper = new DBHelper(this);
        //开启数据库
        helper.openDatabase();

        initView();
        initListener();

        //获取联系人列表 并显示
        users = helper.getAllUser(privacy);
        if (users.size() == 0) {
            setTitle("联系人列表为空");
        }
        //更新界面
        updateListView(userList, R.layout.activity_list_contracts);


    }

    private void initView() {
        //查询文本框
        etSearch = (EditText) findViewById(R.id.et_search);
        //显示用户的ListView
        userList = (ListView) findViewById(R.id.lv_users);
        //添加用户按钮
        btAddUser = (FloatingActionButton) findViewById(R.id.bt_add_user);
        //查询联系人
        etSearch = (EditText) findViewById(R.id.et_search);
        //底部菜单
        deleteUser = (LinearLayout) findViewById(R.id.delete_user);
        //底部菜单删除按钮
        btDeleteUser = (Button) findViewById(R.id.bt_delete_user);
        //查询结果提示
        searchResult = (RelativeLayout) findViewById(R.id.search_result);
    }

    public void initListener() {
        // 列表选项点击事件
        userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!isChecking) {
                    HashMap item = (HashMap) parent.getItemAtPosition(position);
                    int _id = Integer.parseInt(String.valueOf(item.get("_id")));

                    Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                    User user = new User();
                    user.set_id(Integer.parseInt(String.valueOf(item.get("_id"))));
                    user.setUsername(String.valueOf(item.get("name")));
                    user.setCompany(String.valueOf(item.get("company")));
                    user.setPosition(String.valueOf(item.get("position")));
                    user.setFamilyPhone(String.valueOf(item.get("family_phone")));
                    user.setMobilePhone(String.valueOf(item.get("mobile_phone")));
                    user.setOfficePhone(String.valueOf(item.get("office_phone")));
                    user.setOtherContact(String.valueOf(item.get("other_contact")));
                    user.setEmail(String.valueOf(item.get("email")));
                    user.setAddress(String.valueOf(item.get("address")));
                    user.setRemark(String.valueOf(item.get("remark")));
                    user.setZipCode(String.valueOf(item.get("zip_code")));
                    user.setImageId(Integer.parseInt(String.valueOf(item.get("image_id"))));

                    intent.putExtra("user", user);
                    intent.putExtra("position", position);

				/*将position作为请求码传过去  用于标识修改项的位置*/
                    startActivityForResult(intent, position);
//                    turnToActivity(DetailActivity.class, -1);

                } else {
                    if (deleteId == null) {
                        deleteId = new ArrayList<>();
                    }
                    HashMap item = (HashMap) parent.getItemAtPosition(position);
                    Integer _id = Integer.parseInt(String.valueOf(item.get("_id")));

                    LinearLayout r = (LinearLayout) view;
                    ImageView markedView = (ImageView) r.getChildAt(2);

                    //图片切换
                    if (markedView.getDrawable().getCurrent().getConstantState()
                            == getResources().getDrawable(R.drawable.check).getConstantState()) {
                        markedView.setImageResource(R.drawable.no_check);
                        deleteId.remove(_id);
                    } else {
                        markedView.setImageResource(R.drawable.check);
                        deleteId.add(_id);
                    }
                }
            }
        });

        //长按事件
        userList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (!isChecking) {
                    // 非 checking 状态，进入 checking 状态
                    updateListView(userList, R.layout.activity_list_contracts_checking);
                    userList.setSelection(position);
                    btAddUser.setVisibility(View.GONE);
                    deleteUser.setVisibility(View.VISIBLE);
                    isChecking = true;
                }
                return true;
            }
        });


        //搜索框事件
        etSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                String condition = etSearch.getText().toString();
                if (condition.equals("")) {
                    userList.setAdapter(adapter);
                }
                DBHelper helper = new DBHelper(MainActivity.this);
                users = helper.getUsers(condition, privacy);
                SimpleAdapter searchAdapter = new SimpleAdapter(
                        MainActivity.this,
                        users,
                        R.layout.activity_list_contracts,
                        new String[]{"image_id", "name"},
                        new int[]{R.id.image_user, R.id.tv_username});
                userList.setAdapter(searchAdapter);  //将整合好的adapter交给listview，显示给用户看
                if (users.size() == 0) {
                    searchResult.setVisibility(View.VISIBLE);
//                    mainLinearLayout.setBackgroundDrawable(nodata_bg);
//                    setTitle("没有查到任何数据");
                } else {
//                    setTitle("共查到 " + users.size() + " 条记录");
                    searchResult.setVisibility(View.GONE);
//                    mainLinearLayout.setBackgroundDrawable(null);
                }
                return false;
            }
        });

        //添加用户按钮点击
        btAddUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
                turnToActivity(AddUserActivity.class, 1);
            }
        });

        //删除联系人
        btDeleteUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (deleteId == null || deleteId.size() == 0) {
                    Toast.makeText(MainActivity.this, "没有标记任何记录", Toast.LENGTH_SHORT).show();
                } else {
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("确定要删除标记的" + deleteId.size() + "条记录吗?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    DBHelper helper = new DBHelper(MainActivity.this);
                                    helper.deleteMarked(deleteId);
                                    //重置视图
                                    users = helper.getAllUser(privacy);
                                    updateListView(userList, R.layout.activity_list_contracts);
                                    userList.setSelection(userList.getSelectedItemPosition());
                                    deleteId.clear();
                                    btAddUser.setVisibility(View.VISIBLE);
                                    deleteUser.setVisibility(View.GONE);
                                    deleteId.clear();
                                    isChecking = false;
                                }
                            })
                            .setNegativeButton("取消", null)
                            .create()
                            .show();
                }
            }
        });

    }

    /**
     * 跳转掉指定 Activity
     *
     * @param cls         The component class that is to be used for the intent.
     * @param requestCode If >= 0, to launch an activity for result, else to launch activity directly
     */
    public void turnToActivity(Class<?> cls, int requestCode) {
        Intent intent = new Intent(MainActivity.this, cls);
        if (requestCode >= 0) {
            startActivityForResult(intent, requestCode);
        } else {
            startActivity(intent);
        }
    }

    /**
     * 更新 ListView 界面
     */
    public void updateListView(ListView view, int resource) {
        adapter = new SimpleAdapter(MainActivity.this,
                users,
                resource,
                new String[]{"image_id", "name"},
                new int[]{R.id.image_user, R.id.tv_username});
        view.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //清除deleteId的内容
        if (deleteId != null) {
            deleteId.clear();
        }
        //当resultCode==3时代表添加了一个用户返回，当resultCode==4的时候代表修改了用户，或者删除了用户，其他条件代表数据没有变化
        if (resultCode == 3 || resultCode == 4) {
            DBHelper helper = new DBHelper(this);
            users = helper.getAllUser(privacy);
            adapter = new SimpleAdapter(this,
                    users,
                    R.layout.activity_list_contracts,
                    new String[]{"image_id", "name"},
                    new int[]{R.id.image_user, R.id.tv_username});
//            if (list.size() > 0) {
//                mainLinearLayout.setBackgroundDrawable(null);
//            }
        }

        userList.setAdapter(adapter); //将整合好的adapter交给listview，显示给用户看

        /**
         * resultCode只有3、4、5
         * 当等于4或者5的时候，代表由UserDetail转过来的。在转向UserDetail的时候，requestCode的值设置的是选中项的位置
         */
        if (resultCode == 3) {
            userList.setSelection(users.size());
        } else {
            userList.setSelection(requestCode);
        }
    }

    @Override
    public void onBackPressed() {

        if (isChecking) {

            updateListView(userList, R.layout.activity_list_contracts);
            userList.setSelection(userList.getSelectedItemPosition());
            btAddUser.setVisibility(View.VISIBLE);
            deleteUser.setVisibility(View.GONE);
            isChecking = false;
            if (deleteId != null) {
                deleteId.clear();
            }

        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (adapter != null) {
            adapter = null;
        }
        if (users != null) {
            users = null;
        }
        if (userList != null) {
            userList = null;
        }

        if (DBHelper.dbInstance != null) {
            DBHelper.dbInstance.close();
            DBHelper.dbInstance = null;
        }

        Log.i(TAG, "-----------onDestroy is called!!!");
    }
}
